#include "ui.h"
#include "ui_menu.h"
#include "ui_data.h"
#include "ui_chart.h"
#include "ui_set.h"
#include "global.h"


typedef void (*t_ui_enter_func)(void *para);
typedef void (*t_ui_handle_func)(void);
typedef void (*t_ui_exit_func)(void);

struct ui_func
{
    t_ui_enter_func enter;
    t_ui_handle_func handle;
    t_ui_exit_func exit;
};
static struct ui_func ui_func_tbl[E_UI_MAX] = 
{
    [E_UI_MENU] = {.enter=ui_menu_init, .handle=NULL, .exit=ui_menu_exit},
    [E_UI_MONITOR_DATA] = {.enter=ui_data_init, .handle=ui_data_handle, .exit=ui_data_exit},
    [E_UI_MONITOR_CHART] = {.enter=ui_chart_init, .handle=ui_chart_handle, .exit=ui_chart_exit},
    [E_UI_SETTING] = {.enter=ui_set_init, .handle=ui_set_handle, .exit=ui_set_exit},
};
static e_ui_type g_ui_type = E_UI_MAX;
static e_ui_type g_ui_type_old = E_UI_MAX;
static void *g_para;
static lv_timer_t *g_timer;
static volatile uint32_t no_opera_tick = 0;


static void ui_timer_cb(struct _lv_timer_t *timer)
{
    ui_handle();
    if (g_ui_type != E_UI_MONITOR_DATA)
    {
        no_opera_tick ++;
        if (no_opera_tick > UI_NO_OPERA_TIME)
        {
            no_opera_tick = 0;
            ui_enter(E_UI_MONITOR_DATA, E_UI_DATA_PM2D5);
        }
    }
}

void ui_init(void)
{
    g_timer = lv_timer_create(ui_timer_cb, 1000, NULL);
}

bool ui_enter(e_ui_type type, void *para)
{
    if (type >= E_UI_MAX)
    {
        return false;
    }

    if (g_ui_type < E_UI_MAX)
    {
        if (ui_func_tbl[g_ui_type].exit != NULL)
        {
            ui_func_tbl[g_ui_type].exit();
        }
    }

    g_ui_type_old = g_ui_type;

    if (ui_func_tbl[type].enter != NULL)
    {
        ui_func_tbl[type].enter(para);
    }

    if (ui_func_tbl[type].handle != NULL)
    {
        ui_func_tbl[type].handle();
    }

    g_ui_type = type;
    g_para = para;

    return true;
}

void ui_handle(void)
{
    if (ui_func_tbl[g_ui_type].handle != NULL)
    {
        ui_func_tbl[g_ui_type].handle();
    }
}

void ui_return(void)
{
    ui_enter(g_ui_type_old, g_para);
}

void ui_input_feedback(struct _lv_indev_drv_t *dev, uint8_t code)
{
    no_opera_tick = 0;
}

